package com.gitee.classload;

import java.io.*;

/**
 * @author ming.yan-1
 * @version V1.0
 * @Title com.gitee.classload
 * @Description
 * @date 2018/9/6  下午6:55
 */
public class MyClassLoader extends ClassLoader{

    private String rootDir;

    public MyClassLoader( String rootDir) {
        this.rootDir = rootDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = getFileData(name);
        if(bytes == null){
            throw new ClassNotFoundException();
        }else {
            Class<?>  c = this.defineClass(name,bytes,0,bytes.length);
            this.resolveClass(c);//解析，可以不解析，等class初始化的时候在解析
            return c;
        }
    }

    private byte[] getFileData(String name){
        String path = rootDir+ File.separatorChar+name.replace('.', File.separatorChar)+".class";
        try {
            InputStream is = new FileInputStream(path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] temp = new byte[4098];
            int n = 0;
            while ((n = is.read(temp))!=-1){
                out.write(temp);
            }
            return out.toByteArray();
        } catch (FileNotFoundException e) {
            //特殊处理
        } catch (IOException e) {
            //特殊处理
        }
        return null;
    }

}
